package com.ghostwan.androears;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.ghostwan.androears.customObject.Song;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.DeadObjectException;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class MusicPlayerService extends Service
{

	protected final static String TAG = "MusicPlayerService";

	private MediaPlayer mPlayer;
	public static final int PLAYER_ID = 1337;
	public static final String SHUTDOWN = "SHUTDOWN";
	public static final String BROADCAST_ACTION = "com.ghostwan.androears.MusicPLayerUpdateEvent";
	public List<Song> mSongList;
	private int mCurrentPosition;
	public NotificationManager mNotificationManager;
	public Notification mNotification;
	private static final int NOTIFY_ID = R.layout.musicplayer;
	private Intent mBroadcast = new Intent(BROADCAST_ACTION);
	private boolean mIsStopped;
	private boolean mIsRandom;
	private Random mRandom;

	private PendingIntent mContentIntent;
	/**
	 * @see android.app.Service#onBind(Intent)
	 */
	@Override
	public IBinder onBind(Intent intent)
	{
		return mBinder;
	}

	@Override
	public void onCreate()
	{
		super.onCreate();
		mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		mPlayer = new MediaPlayer();
		mSongList = new ArrayList<Song>();
		mIsStopped = true;
		mIsRandom = false;
		mNotification = new Notification(android.R.drawable.ic_media_play, "Andro\'s ears", 
			System.currentTimeMillis());
		Context context = getApplicationContext();
		CharSequence contentTitle = "My notification";
		CharSequence contentText = "Hello World!";
		Intent notificationIntent = new Intent(this, AndroEars.class);
		mContentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
		//mNotification.setLatestEventInfo(context, contentTitle, contentText, mContentIntent);
		
		mPlayer.setOnCompletionListener(new OnCompletionListener()
		{

			public void onCompletion(MediaPlayer arg0)
			{
				nextSong();
			}
		});
	}

	@Override
	public void onDestroy()
	{
		mPlayer.stop();
		mPlayer.release();
	}

	private final MusicPlayerInterface.Stub mBinder = new MusicPlayerInterface.Stub()
	{

		@Override
		public void playList(int position) throws DeadObjectException
		{
			try
			{
				stop();
				mCurrentPosition = position;

			}
			catch (Exception e)
			{
				Log.e(TAG, e.getMessage());
			}
		}

		@Override
		public void clearPlaylist() throws DeadObjectException
		{
			mSongList.clear();
		}

		@Override
		public boolean skipBack() throws DeadObjectException
		{
			return prevSong();

		}

		@Override
		public Song getCurrentSong()
		{
			return mSongList.get(mCurrentPosition);
		}

		
		@Override
		public boolean skipForward() throws DeadObjectException
		{
			return nextSong();
		}

		@Override
		public void pause() throws DeadObjectException
		{
			
			mNotificationManager.cancel(PLAYER_ID);
			mPlayer.pause();
		}

		@Override
		public void stop() throws DeadObjectException
		{
			mNotificationManager.cancel(PLAYER_ID);
			mIsStopped = true;
			mPlayer.stop();
			try
			{
				mBinder.getCurrentSong().mIsPlayed = 0;
			}
			catch (RemoteException e)
			{
				// TODO Auto-generated catch block
				Log.e(TAG, e.getMessage());
			}
		}

		@Override
		public int addSongPlaylist(Song song) throws RemoteException
		{
			mSongList.add(song);
			return mSongList.size() - 1;

		}

		@Override
		public void play() throws RemoteException
		{

			Song song = getCurrentSong();
			CharSequence contentTitle = song.mSongName;
			CharSequence contentText = song.mAlbumName+"\n"+song.mArtistName;

			mNotification.setLatestEventInfo(getApplicationContext(), 
				contentTitle, contentText, mContentIntent);
			mNotificationManager.notify(PLAYER_ID, mNotification);
			
			if (mIsStopped)
			{

				try
				{
					mPlayer.reset();
					mPlayer.setDataSource(mBinder.getCurrentSong().mPath);
					mPlayer.prepare();
				}
				catch (IOException e)
				{
					// TODO Auto-generated catch block
					Log.e(TAG, e.getMessage());
				}

			}
			mBinder.getCurrentSong().mIsPlayed = 1;
			mIsStopped = false;
			mPlayer.start();

		}

		@Override
		public List<Song> getSongList() throws RemoteException
		{
			return mSongList;
		}

		@Override
		public void removeSongPlayList(int position) throws RemoteException
		{
			if(getCurrentSong().equals(mSongList.get(position))) stop();
			mSongList.remove(position);

		}

		@Override
		public long getElapsedTime() throws RemoteException
		{
			return mPlayer.getCurrentPosition();
		}

		@Override
		public void seekTo(int msec) throws RemoteException
		{
			mPlayer.seekTo(msec);
		}

		@Override
		public int getCurrentPosition() throws RemoteException
		{
			return mCurrentPosition;
		}

	};

	private boolean nextSong()
	{
		// Check if last song or not
		if (mCurrentPosition >= mSongList.size() - 1)
		{
			mCurrentPosition = mSongList.size() - 1;
			return false;
			// nm.cancel(NOTIFY_ID);
		}
		else
		{
			try
			{

				mBinder.stop();
				if(mIsRandom) 
					mCurrentPosition = mRandom.nextInt(mSongList.size());
				else 
					mCurrentPosition++;
				mBinder.play();
			}
			catch (RemoteException e)
			{
				// TODO Auto-generated catch block
				Log.e(TAG, e.getMessage());
			}

			mBroadcast.removeExtra("com.ghostwan.androears.MusicPLayerAction");
			mBroadcast.putExtra("com.ghostwan.androears.MusicPLayerAction",
					"next");
			sendBroadcast(mBroadcast);
			return true;
		}
	}

	private boolean prevSong()
	{
		if (mCurrentPosition <= 0)
		{
			mCurrentPosition = 0;
			return true;
		}
		else
		{
			try
			{
				mBinder.stop();
				mCurrentPosition--;
				mBinder.play();
			}
			catch (RemoteException e)
			{
				// TODO Auto-generated catch block
				Log.e(TAG, e.getMessage());
			}

			mBroadcast.removeExtra("com.ghostwan.androears.MusicPLayerAction");
			mBroadcast.putExtra("com.ghostwan.androears.MusicPLayerAction",
					"previous");
			sendBroadcast(mBroadcast);
			return false;
		}
	}

}
